import 'package:loxen/dialog/dialog_utils.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/material/material_order_mode.dart';
import 'package:loxen/utils/color.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/time_util.dart';
import 'package:loxen/view/material/material_order_receive/order_detail_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pagewise/flutter_pagewise.dart';
import 'package:rxdart/rxdart.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/mode/base_mode.dart';
import 'package:loxen/mode/mine/order_list_mode.dart';
import 'package:loxen/utils/app_enum_util.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:url_launcher/url_launcher.dart';

class _ViewModel extends BaseViewModel {
  OrderListType orderListType;
  int pageSize = 4;

  Map<String, List<Order>> map = {};

  _ViewModel(this.orderListType);

  String getStatus() {
    String status;
    switch (orderListType) {
      case OrderListType.ALL:
        status = '0';
        break;
      case OrderListType.TO_BE_CONFIRMED:
        status = '1';
        break;
      case OrderListType.HAVE_IN_HAND:
        status = '2';
        break;
      case OrderListType.COMPLETED:
        status = '3';
        break;
      case OrderListType.CLOSED:
        status = '4';
        break;
    }
    return status;
  }

  void loadData() {
    ApiService.orderList(status: getStatus())
        .doOnListen(() {
          mState = BaseState.LOADING;
          notifyListeners();
        })
        .flatMap((value) {
          return compute(deCode, value.data).asStream();
        })
        .flatMap((value) => Stream.value(value?.data))
        .listen((event) {
          if (event != null && event.count > 0) {
            map.putIfAbsent('0', () => event.results);
            mState = BaseState.CONTENT;
          } else {
            mState = BaseState.EMPTY;
          }
        }, onError: (error, stack) {
          mState = BaseState.FAIL;
          print(error);
          print(stack);
        }, onDone: () => notifyListeners());
  }

  void cancelOrder(Order order, Function() onSuccess) {
    ApiService.cancelOrder(order.id.toString()).listen((event) {
      map.forEach((key, value) {
        value.remove(order);
      });
      if (onSuccess != null) onSuccess.call();
    }, onError: (error, stack) {
      print(error);
      print(stack);
    });
  }

  Future<List<Order>> nextData(int index) async {
    if (map.containsKey('$index')) {
      return map['$index'];
    } else {
      var data = await ApiService.orderList(status: getStatus(), page: '${index + 1}')
          .flatMap((value) => compute(deCode, value.data).asStream())
          .flatMap((value) => Stream.value(value?.data))
          .flatMap((value) => Stream.value(value?.results))
          .first;
      map.putIfAbsent('$index', () => data);
      return data;
    }
  }

  static BaseMode<OrderList> deCode(dynamic jsonRes) {
    return BaseMode<OrderList>(jsonRes);
  }
}

class OrderListPage extends StatefulWidget {
  final OrderListType orderListType;

  const OrderListPage({Key key, this.orderListType}) : super(key: key);

  @override
  _OrderListPageState createState() => _OrderListPageState();
}

class _OrderListPageState extends State<OrderListPage> with AutomaticKeepAliveClientMixin {
  ///2020-09-02 07:00:00

  PagewiseLoadController pageLoadController;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ChangeNotifierProvider<_ViewModel>(
      create: (BuildContext context) {
        var model = _ViewModel(widget.orderListType);
        model.loadData();
        pageLoadController =
            PagewiseLoadController<Order>(pageFuture: model.nextData, pageSize: model.pageSize);
        return model;
      },
      child: Builder(
        builder: (BuildContext context) {
          var state = context.select<_ViewModel, BaseState>((value) => value.mState);
          print("build Content $state}");
          Widget page;
          switch (state) {
            case BaseState.FAIL:
              page = FailWidget();
              break;
            case BaseState.EMPTY:
            case BaseState.LOADING:
            // page = LoadingWidget();
            // break;
            case BaseState.CONTENT:
              page = PagewiseListView<Order>(
                addAutomaticKeepAlives: false,
                loadingBuilder: (_) => MySubassembly.getLoadingItem(),
                noItemsFoundBuilder: (_) => MySubassembly.getNullItem(msg: '没有更多订单'),
                itemBuilder: (context, entity, index) {
                  return createCard(context, entity);
                },
                pageLoadController: pageLoadController,
              );
              break;
          }
          return RefreshIndicator(
            onRefresh: () async {
              context.read<_ViewModel>().map.clear();
              pageLoadController.reset();
              return true;
            },
            child: page,
          );
        },
      ),
    );
  }

  Widget createCard(BuildContext context, Order order) {
    return Container(
      margin: EdgeInsets.only(top: 16.h, right: 20.w, left: 20.w),
      child: TweenAnimationBuilder(
          curve: Curves.bounceIn,
          tween: Tween<double>(begin: 0, end: 1),
          duration: Duration(milliseconds: 500),
          child: Container(
            padding: EdgeInsets.only(right: 20.w, left: 20.w),
            width: double.infinity,
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.only(top: 30.h, bottom: 30.h),
                  child: Row(
                    children: [
                      CachedNetworkImage(
                        imageUrl: ImageUrlUtil.getClean(order?.brand?.logo),
                        height: 24.h,
                        fit: BoxFit.fitHeight,
                      ),
                      Expanded(child: Constants.empty),
                      Text(
                        order.getState(),
                        style: TextStyle(
                          fontSize: 22.sp,
                          color: Color(0xfffcad08),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  height: 150.h,
                  margin: EdgeInsets.only(bottom: 40.h),
                  child: GridView.count(
                    crossAxisCount: 1,
                    mainAxisSpacing: 20.w,
                    scrollDirection: Axis.horizontal,
                    physics: NeverScrollableScrollPhysics(),
                    children: _initItem(context, order.product),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(bottom: 40.h),
                  child: Row(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(right: 50.w),
                        child: Text(
                          '领样方式',
                          style: TextStyle(
                            fontSize: 28.sp,
                            color: Colours.dark_text_gray,
                          ),
                        ),
                      ),
                      Text(
                        order.getMode(),
                        style: TextStyle(
                          fontSize: 28.sp,
                          color: Colours.main_text,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(bottom: 40.h),
                  child: Row(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(right: 50.w),
                        child: Text(
                          '送样时间',
                          style: TextStyle(
                            fontSize: 28.sp,
                            color: Colours.dark_text_gray,
                          ),
                        ),
                      ),
                      Text(
                        TimeUtil.getStringTime(order.startTime, order.endTime),
                        style: TextStyle(
                          fontSize: 28.sp,
                          color: Colours.main_text,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(bottom: 30.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      order.isCancel()
                          ? Padding(
                              padding: EdgeInsets.only(right: 20.w),
                              child: Material(
                                color: Colours.bg_color,
                                child: InkWell(
                                  onTap: () async {
                                    if (order.status == '1') {
                                      var data = await showDialog(
                                          context: context,
                                          builder: (context) {
                                            return DialogUtil.showMessageDialog(
                                                context, '取消订单', '是否取消订单?');
                                          });
                                      if (data != null && data) {
                                        Provider.of<_ViewModel>(context, listen: false)
                                            .cancelOrder(order, () {
                                          pageLoadController.loadedItems.remove(order);
                                          pageLoadController.retry();
                                        });
                                      }
                                    } else {
                                      var data = await showDialog(
                                        context: context,
                                        builder: (context) => Dialog(
                                          child: Container(
                                            width: 420.w,
                                            child: Column(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                Padding(
                                                  padding: EdgeInsets.only(top: 40.h, bottom: 40.h),
                                                  child: Text(
                                                    '请联系服务中心取消订单',
                                                    style: TextStyle(color: Colors.black),
                                                  ),
                                                ),
                                                Divider(
                                                  height: 1.h,
                                                ),
                                                Container(
                                                  height: 80.h,
                                                  child: Row(
                                                    children: [
                                                      Expanded(
                                                        child: FlatButton(
                                                            onPressed: () => Navigator.pop(context),
                                                            child: Text(
                                                              '取消',
                                                              style: TextStyle(
                                                                color: Colours.dark_text_gray,
                                                                fontSize: 28.sp,
                                                              ),
                                                            )),
                                                      ),
                                                      Container(
                                                        width: 1.w,
                                                        height: double.infinity,
                                                        color: Color(0xFFE7E7E7),
                                                      ),
                                                      Expanded(
                                                        child: FlatButton(
                                                            onPressed: () =>
                                                                Navigator.pop(context, true),
                                                            child: Text(
                                                              '拨号',
                                                              style: TextStyle(
                                                                color: Colours.app_main,
                                                                fontSize: 28.sp,
                                                              ),
                                                            )),
                                                      ),
                                                    ],
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                      );
                                      if (data != null && data) {
                                        String url = 'tel:${order.mode}';
                                        bool canLaunchUrl = await canLaunch(url);
                                        if (!canLaunchUrl) {
                                          Toast.show('拨号失败', context);
                                          return;
                                        }
                                        await launch(url);
                                      }
                                    }
                                  },
                                  borderRadius: BorderRadius.all(Radius.circular(66.w)),
                                  child: Container(
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(Radius.circular(66.h)),
                                      border: Border.all(color: Color(0xffE7E7E7), width: 1.w),
                                    ),
                                    width: 170.w,
                                    height: 66.h,
                                    child: Center(
                                        child: Text(
                                      '取消订单',
                                      style: TextStyle(
                                        fontSize: 28.sp,
                                        color: Colours.text_gray,
                                      ),
                                    )),
                                  ),
                                ),
                              ),
                            )
                          : Constants.empty,
                      Material(
                        borderRadius: BorderRadius.all(Radius.circular(66.w)),
                        color: Colours.app_main,
                        child: InkWell(
                          onTap: () {
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (_) => OrderDetailWidget(id: order.id.toString())));
                          },
                          borderRadius: BorderRadius.all(Radius.circular(66.w)),
                          child: Container(
                            width: 170.w,
                            height: 66.h,
                            child: Center(
                                child: Text(
                              '订单详情',
                              style: TextStyle(
                                fontSize: 28.sp,
                                color: Colours.bg_color,
                              ),
                            )),
                          ),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          builder: (_, double data, child) {
            return Card(
              elevation: data * 5,
              child: child,
            );
          }),
    );
  }

  List<Widget> _initItem(BuildContext context, List<Product> products) {
    List<Widget> list = [];
    if (products != null && products.length > 3) {
      for (int i = 0; i < 3; i++) {
        Product product = products[i];
        list.add(ClipRRect(
            borderRadius: BorderRadius.circular(10.w),
            child: CachedNetworkImage(
              imageUrl: ImageUrlUtil.getClean(product.cover),
              placeholder: (_, __) => Constants.loadingIcon(),
              fit: BoxFit.cover,
              width: double.infinity,
              height: double.infinity,
            )));
      }
      list.add(Container(
        child: Row(
          children: [
            Image.asset(
              'images/ellipsis.png',
              width: 44.w,
              height: 44.w,
            ),
          ],
        ),
      ));
    } else {
      for (var product in products) {
        list.add(ClipRRect(
            borderRadius: BorderRadius.circular(10.w),
            child: CachedNetworkImage(
              imageUrl: ImageUrlUtil.getClean(product.cover),
              placeholder: (_, __) => Constants.loadingIcon(),
              fit: BoxFit.cover,
              width: double.infinity,
              height: double.infinity,
            )));
      }
    }

    return list;
  }
}
